package controller.manager;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.CinemaUser;
import util.HibernateUtil;
import util.MD5_Encoder;
import databaseLayer.CinemaUser_db;

/**
 * Servlet implementation class OfficerManagementServlet
 */
public class OfficerManagementServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("action");

        if (action == null) {
            listOfficers(request, response);
        } else if (action.equalsIgnoreCase("create")) {
            createOfficer(request, response);
        } else if (action.equalsIgnoreCase("delete")) {
            deleteOfficer(request, response);
        } else if (action.equalsIgnoreCase("update")) {
            updateOfficer(request, response);
        } else {
            listOfficers(request, response);
        }
    }

    private void updateOfficer(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String newPassword = request.getParameter("newPassword");

        if (newPassword == null || newPassword.equals("")) {
            // forward to input page
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/updateOfficerInput.jsp");
            requestDispatcher.forward(request, response);
        } else {
            try {
                String md5_password = MD5_Encoder.encode(newPassword);

                CinemaUser updatedOfficer = new CinemaUser(username,
                        md5_password, "officer");
                HibernateUtil.update(updatedOfficer);

                HttpSession session = request.getSession();
                session.setAttribute("message",
                        "Update a new officer successfully!");

                // forward to result page
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/manipulateResult.jsp");
                requestDispatcher.forward(request, response);
            } catch (Exception ex) {
                String errorMessage = ex.getMessage();
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", errorMessage);
                // forward to input page
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/updateOfficerInput.jsp");
                requestDispatcher.forward(request, response);
            }
        }
    }

    private void deleteOfficer(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String message;
        try {
            String username = request.getParameter("username");
            CinemaUser target = CinemaUser_db.selectCinemaUserByUserName(username);
            HibernateUtil.delete(target);
            message = "Delete a officer successfully!";
        } catch (Exception ex) {
            message = ex.getMessage();
        }

        HttpSession session = request.getSession();
        session.setAttribute("message", message);

        // forward to JSP
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/manipulateResult.jsp");
        requestDispatcher.forward(request, response);
    }

    private void createOfficer(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String message;
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            // check empty input
            if (username == null || password == null || username.equals("")
                    || password.equals("")) {
                throw new Exception("Username or password is empty");
            }

            // check whether the user name already exists
            if (CinemaUser_db.isUserExist(username) == true) {
                throw new Exception("Username \"" + username
                        + "\" has already been used");
            }

            // add new officer
            String md5_password = MD5_Encoder.encode(password);
            CinemaUser newOfficer = new CinemaUser(username, md5_password,
                    "officer");
            HibernateUtil.insert(newOfficer);
            message = "Create a new officer successfully!";
        } catch (Exception ex) {
            message = ex.getMessage();
        }

        HttpSession session = request.getSession();
        session.setAttribute("message", message);

        // forward to JSP
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/manipulateResult.jsp");
        requestDispatcher.forward(request, response);
    }

    private void listOfficers(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        List<CinemaUser> listOfficer = CinemaUser_db.selectCinemaUsersByRole("officer");

        HttpSession session = request.getSession();
        session.setAttribute("listOfficer", listOfficer);

        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/officerManagement/listOfficers.jsp");
        requestDispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public OfficerManagementServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}
